package com.gec.news.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gec.news.entity.Comments;
import com.gec.news.entity.News;
import com.gec.news.entity.Topic;
import com.gec.news.service.CommentsService;
import com.gec.news.service.NewsService;
import com.gec.news.service.TopicService;
import com.gec.news.vo.NewsQueryVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class NewsController {
    @Autowired
    NewsService newsService;

    @Autowired
    TopicService topicService;

    @Autowired
    CommentsService commentsService;
    //表示他这个方法的接受请求的url路径的注解

    @RequestMapping(value = {"/","/index.html","/home.html"})
    public String index(Model model, NewsQueryVo newsQueryVo){
        //调用业务逻辑代码，去查询出左侧的新闻分类标题信息
        List<News> newsList1 = newsService.getNewsListByTopicId(1,6);
        List<News> newsList2 = newsService.getNewsListByTopicId(2,6);
        List<News> newsList3 = newsService.getNewsListByTopicId(5,6);
       //将这些数据放到模型代码中 通过model对象携带到页面模板中 然后将数据渲染到页面去
        model.addAttribute("newsList1",newsList1);
        model.addAttribute("newsList2",newsList2);
        model.addAttribute("newsList3",newsList3);
        //查询出所有分类信息
        List<Topic> topicList =topicService.list();
        model.addAttribute("topicList",topicList);
        //创建分页查询对象 帮助分页查询信息
        //设置页码和分页的数量
        //要查询出中间部分的新闻标题信息 分页查询的 构建分页查询的对象
        IPage<News> page = new Page<>(newsQueryVo.getPageNo(),newsQueryVo.getPageSize());
        //调用根据分页对象查询 新闻列表信息的业务逻辑代码
        //Ipage<News>类型的对象是包含了分页信息的查询结果 页码 总共有多少条记录都封装在里面
        page=newsService.getNewsListByPage(page,newsQueryVo);
        model.addAttribute("page",page);
        //设置分页信息参数
        model.addAttribute("newVo",newsQueryVo);
        return "index";
    }

    @RequestMapping("/news/detail/{nid}")
    public String detail(@PathVariable("nid") int nid ,Model model){
        //调用业务逻辑代码，去查询出左侧的新闻分类标题信息
        List<News> newsList1 = newsService.getNewsListByTopicId(1,6);
        List<News> newsList2 = newsService.getNewsListByTopicId(2,6);
        List<News> newsList3 = newsService.getNewsListByTopicId(5,6);
        //将这些数据放到模型代码中 通过model对象携带到页面模板中 然后将数据渲染到页面去
        model.addAttribute("newsList1",newsList1);
        model.addAttribute("newsList2",newsList2);
        model.addAttribute("newsList3",newsList3);
        //利用mybatis plus 框架中提供的基础方法根据id查询对应的新闻信息的方法
        News news = newsService.getById(nid);
        //将查询出来的数据  放到model模型数据中，通过springMVC渲染到detail.html模板页面中
        model.addAttribute("news",news);
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        //根据新闻编号查询新闻信息==》
        // select * from comments where cnid = 'nid'
        wrapper.eq("cnid",nid);//where cnid = 'nid'
        List<Comments> commentsList = commentsService.list(wrapper);
        model.addAttribute("commentsList",commentsList);
        return "news/detail";
    }

    @RequestMapping("/news/manager")
    public String manager(NewsQueryVo vo,Model model){
        IPage<News> page = new Page<>(vo.getPageNo(), vo.getPageSize());
        page = newsService.getNewsListByPage(page, vo);
        model.addAttribute("page",page);
        return "admin";
    }

    @RequestMapping("/news/add.html")
    public String toAdd(Model model){
        List<Topic> list = topicService.list();
        model.addAttribute("topicList",list);
        return "news/add";
    }

    @RequestMapping("/news/add")
    public String add(News news,@PathVariable("file")MultipartFile file){
        try{
            System.out.println(file);
            String path = "H:/Web实训/upload/";
            String originalFileName = file.getOriginalFilename();
            String extension= FilenameUtils.getExtension(originalFileName);
            String newFileName = UUID.randomUUID().toString().replace("'","")+"."+extension;
            String dataPath = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String finalName = dataPath+"/"+newFileName;
            File dataFile = new File(path,finalName);
            if (!dataFile.getParentFile().exists()){
                dataFile.getParentFile().mkdir();
            }
            file.transferTo(dataFile);
            news.setNpicPath("http://localhost:7777/upload/"+finalName);
        }catch (Exception e){
            e.printStackTrace();
        }
        newsService.save(news);
        return "redirect:/news/manager";
    }

    @RequestMapping("/news/edit")
    public String edit(News news, MultipartFile file){
        try {
            //判断是否有文件
            if(!file.isEmpty()){
                String path = "H:/Web实训/upload/";
                //获取旧名称
                String originalFilename = file.getOriginalFilename();
                //获取扩展名
                String extension = FilenameUtils.getExtension(originalFilename);
                //重命名文件名
                String newFileName = UUID.randomUUID().toString().replace("-","")+"."+ extension;
                //为了解决同一个文件夹下文件过多的问题，使用日期作为文件夹管理
                String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
                //组装最终的文件名
                String finalName = datePath + "/" + newFileName;
                //创建文件对象
                File destFile = new File(path,finalName);
                //判断文件夹是否存在，文件夹不存在则创建该文件夹
                if(!destFile.getParentFile().exists()){
                    destFile.getParentFile().mkdirs();
                }
                //将文件保存到磁盘
                file.transferTo(destFile);
                //图片路径
                news.setNpicPath(finalName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        news.setNmodifyDate(new Date());
        if(newsService.updateById(news)){
            return "redirect:/news/manager";
        }
        return "redirect:/news/edit/"+news.getNid();
    }

//    @RequestMapping("/news/deleteById/{id}")
//    public void deleteById(@PathVariable Integer id, HttpServletResponse response){
//        try {
//            response.setCharacterEncoding("GBK");
//            if(newsService.removeById(id)){
//                response.getWriter().print("<script>alert('删除成功');location.href='/news/manager';</script>");
//            }
//            response.getWriter().print("<script>alert('删除失败');location.href='/news/manager';</script>");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

        @RequestMapping("/news/deleteById/{id}")
    public void deleteById(@PathVariable Integer id, HttpServletResponse response){
        try {
            response.setCharacterEncoding("GBK");
            if(newsService.deleteById(id)){
                response.getWriter().print("<script>alert('删除成功');location.href='/news/manager';</script>");
            }
            response.getWriter().print("<script>alert('删除失败');location.href='/news/manager';</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/news/edit/{nid}")
    public String edit(@PathVariable("nid") int nid,Model model){
        News news = newsService.getById(nid);
        model.addAttribute("news",news);
        List<Topic> topicList = topicService.list();
        model.addAttribute("topicList",topicList);
        return "news/edit";
    }
}
